<template>
  <div class="main-wrapper">
    <div class="cpy-box">
      <el-form
        ref="companyFormRef"
        :rules="rules"
        :disabled="dialogData.isView"
        :model="dialogData.itemInfo"
        label-width="100px"
        label-suffix=" :"
        :hide-required-asterisk="dialogData.isView"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <div class="opt-title-box">
              <div class="info-title">企业基本信息</div>
              <div class="opt">
                <el-button :icon="CirclePlus" @click="handleSubmit" type="primary">保存企业信息</el-button>
              </div>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="公司名称">
              <el-input
                v-model="dialogData.itemInfo.name"
                placeholder="请填写名称"
                disabled
                maxlength="100"
                show-word-limit
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司简称">
              <el-input v-model="dialogData.itemInfo.sname" placeholder="请填写简称" clearable maxlength="20"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="公司性质">
              <!-- <el-select
                v-model="dialogData.itemInfo.nature"
                placeholder="请选择性质"
                style="width: 100%"
              >
                <el-option
                  v-for="item in companyNatureType"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select> -->
              <el-input v-model="dialogData.itemInfo.natureName" placeholder="公司性质" disabled maxlength="100"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属行业">
              <el-select v-model="dialogData.itemInfo.industry" placeholder="请选择所属行业" style="width: 100%">
                <el-option
                  v-for="item in companyIndustryType"
                  :label="item.label"
                  :value="item.value"
                  :key="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="公司类型">
              <el-select v-model="dialogData.itemInfo.companySize" placeholder="请选择公司类型" style="width: 100%">
                <el-option v-for="item in companySizeType" :label="item.label" :value="item.value" :key="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="员工规模">
              <el-select v-model="dialogData.itemInfo.staffSize" placeholder="请选择员工规模" style="width: 100%">
                <el-option
                  v-for="item in companyStaffSizeType"
                  :label="item.label"
                  :value="item.value"
                  :key="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="公司网址">
              <el-input
                v-model="dialogData.itemInfo.website"
                placeholder="请填写公司网址"
                clearable
                maxlength="100"
                show-word-limit
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="公司介绍" maxlength="300" show-word-limit>
              <el-input
                v-model="dialogData.itemInfo.introduce"
                placeholder="请选择公司介绍"
                type="textarea"
                rows="8"
                maxlength="1000"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <div class="opt-title-box">
              <div class="info-title">企业图片 视频</div>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-scrollbar height="200px">
              <UploadImgs
                v-model:fileList="dialogData.fileList"
                :disabled="dialogData.isView"
                :file-size="3"
                width="160px"
                height="160px"
                :api="uploadCpyRes"
              >
                <template #tip> 大小不能超过 3M </template>
              </UploadImgs>
            </el-scrollbar>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="cpy-imgs-box">
      <el-row :gutter="20">
        <el-col :span="24">
          <div class="info-title">企业Logo</div>
        </el-col>
      </el-row>
      <div class="img-box">
        <div class="img">
          <UploadImg
            v-model:imageUrl="dialogData.itemInfo.logoImg"
            :disabled="dialogData.isView"
            :file-size="1"
            width="150px"
            height="150px"
          >
            <template #tip> Logo 大小不能超过 1M </template>
          </UploadImg>
        </div>
      </div>
      <el-row :gutter="20">
        <el-col :span="24">
          <div class="opt-title-box">
            <div class="info-title">企业福利标签</div>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="公司福利 :">
            <el-select
              size="large"
              style="width: 100%"
              v-model="dialogData.itemInfo.tags"
              multiple
              multiple-limit="8"
              placeholder="请选择福利"
            >
              <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="自定义福利 :">
            <div class="cust-tag-wrapper">
              <el-tag
                v-for="tag in dynamicTags"
                :key="tag"
                class="mx-1"
                closable
                :disable-transitions="false"
                @close="handleClose(tag)"
              >
                {{ tag }}
              </el-tag>
              <el-input
                v-if="inputVisible"
                placeholder="请填写"
                ref="InputRef"
                v-model="inputValue"
                class="mx-1 w-20"
                size="small"
                maxlength="4"
                show-word-limit
                @keyup.enter="handleInputConfirm"
                @blur="handleInputConfirm"
              />
              <el-button v-else class="button-new-tag mx-1" size="small" @click="showInput"> + 自定义福利 </el-button>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <el-row :gutter="20">
        <el-col :span="24"> <div class="info-title">企业地址</div></el-col>
      </el-row> -->
      <el-row :gutter="20">
        <el-col :span="24">
          <div class="info-title">营业执照</div>
        </el-col>
      </el-row>
      <div class="img-box">
        <div class="img">
          <div class="alert-box">
            <el-alert
              title="请点击右侧的“Ocr识别 保存营业执照”按钮.请等待系统识别并认证"
              type="error"
              show-icon
              :closable="false"
              effect="dark"
            />
          </div>
          <div class="upload-box">
            <UploadImg
              v-model:imageUrl="dialogData.itemInfo.companyImg"
              :disabled="dialogData.isView"
              :file-size="10"
              width="220px"
              height="220px"
            >
              <template #tip>大小不能超过 10M </template>
            </UploadImg>
          </div>
        </div>
        <div class="opt-wrapper">
          <el-button size="large" type="primary" :icon="Link" @click="handleOcrCompanyLicense">Ocr识别 保存营业执照</el-button>
          <el-alert title="营业执照如有变更，需要平台审核" type="info" :closable="false" />
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, nextTick, reactive, onMounted } from "vue";
import { ElMessage, FormInstance, ElInput } from "element-plus";
import { OptEnum } from "@/biz/eenum/appEnum";
import { DialogParam } from "@/biz/interface/DialogType";
import { CompanyClientEntity } from "@/biz/interface/companyType";
import { getCompanyInfoApi, handleOcrCompanyLicenseApi, saveCompanyApi, saveOcrCompanyLicenseApi } from "@/api/modules/cpy/info";
import UploadImg from "@/components/Upload/Img.vue";
import UploadImgs from "@/components/Upload/Imgs.vue";
import { uploadCpyRes } from "@/api/modules/upload";
import { companyIndustryType, companySizeType, companyStaffSizeType } from "@/biz/datas/companyData";
import { getJobTagsVoListApi } from "@/api/modules/sysjob/jobtag";
import { CirclePlus, Link } from "@element-plus/icons-vue";

const options = ref([] as any);

//页面的数据
interface CompanyDialogOption extends DialogParam {
  //弹出表单的标题
  title: string;
  // 图片
  fileList: [];
  //是否是查看状态，查看状态是不可以提交数据
  isView: boolean;
  //当前的数据对象
  itemInfo: CompanyClientEntity;
  //其它的数据都继续在这里加
}
//提交按钮，避免多次提交
const btnLoading = ref(false);
//当前表单数据在这里初始化
const dialogData = reactive<CompanyDialogOption>({
  optType: OptEnum.UNKNOW,
  title: "",
  isView: false,
  fileList: [],
  itemInfo: {
    name: "",
    sname: "",
    logoImg: "",
    website: "",
    introduce: "",
    tags: [],
    reses: [],
    vouchers: []
  }
});

const inputValue = ref("");
const dynamicTags = ref([]);
const inputVisible = ref(false);
const InputRef = ref<InstanceType<typeof ElInput>>();

const handleClose = (tag: string) => {
  dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1);
};

const showInput = () => {
  inputVisible.value = true;
  nextTick(() => {
    InputRef.value!.input!.focus();
  });
};

const handleInputConfirm = () => {
  if (inputValue.value) {
    if (dynamicTags.value && dynamicTags.value.length > 2) {
      ElMessage.error({ message: `最多可添加3个自定义福利.` });
      return;
    }
    dynamicTags.value.push(inputValue.value);
  }
  inputVisible.value = false;
  inputValue.value = "";
};

//获取当前数据的详情，直接调用接口获取数据
const getItemInfo = async () => {
  let { data } = await getCompanyInfoApi({});
  if (data) {
    dialogData.itemInfo = data as unknown as CompanyClientEntity;

    dialogData.fileList.length = 0;
    let imgIdx = 1;
    if (dialogData.itemInfo.imgs) {
      dialogData.itemInfo.imgs.forEach(img => {
        dialogData.fileList.push({ name: imgIdx, url: img });
        imgIdx = imgIdx + 1;
      });
    }
    if (dialogData.itemInfo.vdos) {
      dialogData.itemInfo.vdos.forEach(vdo => {
        dialogData.fileList.push({ name: imgIdx, url: vdo });
        imgIdx = imgIdx + 1;
      });
    }

    if (dialogData.itemInfo.customTags) {
      dynamicTags.value = dialogData.itemInfo.customTags.split(",");
    } else {
      dynamicTags.value = [];
    }
  } else {
    ElMessage.error({ message: "当前用户不是企业用户" });
  }
};

//数据较验
const rules = reactive({});

// 提交数据（新增/编辑）
const companyFormRef = ref<FormInstance>();
const handleSubmit = () => {
  btnLoading.value = true;
  companyFormRef.value!.validate(async valid => {
    if (!valid) {
      btnLoading.value = false;
      return;
    }
    try {
      //提交数据
      if (dialogData.fileList) {
        dialogData.itemInfo.reses = [];
        dialogData.fileList.forEach(file => {
          // console.log("每个文件, ", file, file.url);
          if (file && file.url) {
            dialogData.itemInfo.reses.push(file.url);
          }
        });
      }

      //最少选择2个标签
      if (!dialogData.itemInfo.tags || dialogData.itemInfo.tags.length < 2) {
        ElMessage.error({ message: `至少选择二项公司福利` });
        return;
      }

      // 填充自定义标签
      dialogData.itemInfo.customTags = "";
      if (dynamicTags.value && dynamicTags.value.length > 0) {
        dialogData.itemInfo.customTags = dynamicTags.value.join(",");
      }

      let res = await saveCompanyApi({
        ...dialogData.itemInfo
      });
      if (res.data) {
        ElMessage.success({ message: `企业信息保存成功！` });
        //刷新列表数据
      }
    } catch (error) {
    } finally {
      btnLoading.value = false;
    }
  });
};

// 识别营业执照信息
const handleOcrCompanyLicense = async () => {
  if (dialogData.itemInfo && dialogData.itemInfo.id) {
    if (dialogData.itemInfo.companyImg) {
      let res = await handleOcrCompanyLicenseApi({
        imgUrl: dialogData.itemInfo.companyImg
      });
      // console.log("识别后的数据", res);
      if (res && res.data) {
        let res2 = await saveOcrCompanyLicenseApi({
          ...res.data,
          companyId: dialogData.itemInfo.id,
          companyImg: dialogData.itemInfo.companyImg
        });
        if (res2 && res2.data) {
          //重新加载一下数据
          getItemInfo();
        }
      }
    } else {
      ElMessage.error({ message: `请上传营业执照` });
    }

    ElMessage.success({ message: `营业执照已上传，等待审核` });
  }
};

//初始化一些参数
onMounted(() => {
  getJobTagsVoListApi({}).then(res => {
    options.value = res.data?.list;
  });

  //获取当前企业的信息
  getItemInfo();
});
</script>
<style scoped lang="scss">
.main-wrapper {
  display: flex;
  width: 100%;
  height: 100%;
  .cpy-box {
    background: #fff;
    width: calc(60%);
    padding: 0 15px;
  }
  .cpy-imgs-box {
    background: #fff;
    padding: 0 15px;
    width: calc(45% - 20px);
    margin-left: 0px;
    // border: 1px solid red;

    .img-box {
      display: flex;
      align-items: center;
      justify-content: center;

      .img {
        display: flex;
        align-items: center;
        justify-content: center;
        flex: 1;
        flex-direction: column;
        // border: 1px solid red;

        .alert-box {
          width: 100%;
        }
      }

      .opt-wrapper {
        // border: 1px solid green;
        width: 260px;
        margin-left: 2rem;
      }
    }
  }
}

.cust-tag-wrapper {
  border: 1px solid var(--el-color-info-light-7);
  width: 100%;
  height: 40px;
  line-height: 40px;
  border-radius: 4px;

  display: flex;
  align-items: center;
  // justify-content: center;

  .mx-1 {
    margin: 0 5px;
  }

  .w-20 {
    width: 120px;
  }

  .button-new-tag {
    width: 120px;
  }
}
</style>
